package com.cn.shchuangge.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cn.shchuangge.been.UpDataInfoBeen;
import com.cn.shchuangge.content.URIpsot;
import com.cn.shchuangge.projectwork.BasicActivity;
import com.cn.shchuangge.projectwork.R;
import com.cn.shchuangge.ui.fragment.BeasicFragment;
import com.cn.shchuangge.uitls.GsonUtil;
import com.cn.shchuangge.uitls.HttpUtil;
import com.cn.shchuangge.uitls.PackageUtil;
import com.cn.shchuangge.uitls.ToastMake;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import okhttp3.Response;

import static com.cn.shchuangge.projectwork.R.id.first_home_text;

public class MainActivity extends BasicActivity {
    //这是安装界面的请求码
    private static final int    REQUEST_INSTALL = 100;
    private static final String TAG             = "MainActivity";
    @InjectView(R.id.mian_mian_mian)
    FrameLayout  mianMianMian;
    @InjectView(R.id.first_home_image)
    ImageView    firstHomeImage;
    @InjectView(R.id.first_home_text)
    TextView     firstHomeText;
    @InjectView(R.id.first_home_home)
    LinearLayout firstHomeHome;
    @InjectView(R.id.second_shopping_image)
    ImageView    secondShoppingImage;
    @InjectView(R.id.second_shopping_text)
    TextView     secondShoppingText;
    @InjectView(R.id.second_shopping_shopping)
    LinearLayout secondShoppingShopping;
    @InjectView(R.id.tired_bag_image)
    ImageView    tiredBagImage;
    @InjectView(R.id.tired_bag_text)
    TextView     tiredBagText;
    @InjectView(R.id.tired_bag_bag)
    LinearLayout tiredBagBag;
    @InjectView(R.id.four_me_image)
    ImageView    fourMeImage;
    @InjectView(R.id.four_me_text)
    TextView     fourMeText;
    @InjectView(R.id.four_me_me)
    LinearLayout fourMeMe;
    @InjectView(R.id.bottom_navigation_bar)
    LinearLayout bottomNavigationBar;
    //记录两次回退键直接退出
    private long tempTime = 0;
    private UpDataInfoBeen mInfoBeen;
    private boolean        mEquals;
    private InputStream      mInputStream  = null;
    private FileOutputStream mOutputStream = null;
    private ProgressDialog mProgressDialog;
    private long           greelong;
    private File           mAPKfile;

    private FragmentTransaction mFragmentTransaction;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        //6.0新特性，动态获取权限
        getUserPermission();

        //进行版本更新
        initData();
        //对控件进行操作
        initView();
        //初始化默认所有的按钮背景都是灰色的
        noPressed();
        //默认首页先被选中
        mFragmentTransaction = getSupportFragmentManager().beginTransaction();
        mFragmentTransaction.add(R.id.mian_mian_mian, FrogmentFactory.getFragment(0), "one").commit();
        //按钮背景也要改变
        //TODO:
        firstHomeText.setTextColor(Color.parseColor("#000000"));
        firstHomeImage.setImageResource(R.mipmap.home_on);
    }

    /**
     *将所有的字体颜色设置为未选中
     */
    private void noPressed() {
        firstHomeText.setTextColor(Color.parseColor("#9c9c9c"));
        secondShoppingText.setTextColor(Color.parseColor("#9c9c9c"));
        tiredBagText.setTextColor(Color.parseColor("#9c9c9c"));
        fourMeText.setTextColor(Color.parseColor("#9c9c9c"));

        firstHomeImage.setImageResource(R.mipmap.home_off);
        secondShoppingImage.setImageResource(R.mipmap.shopping_off);
        tiredBagImage.setImageResource(R.mipmap.shopping_bag_off);
        fourMeImage.setImageResource(R.mipmap.mine_on);
    }

    private void initView() {


    }

    @OnClick({R.id.first_home_home, R.id.second_shopping_shopping, R.id.tired_bag_bag, R.id.four_me_me})
    public void onViewClicked(View view) {
        //点击之前隐藏所有的fragment
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < 4; i++) {
            BeasicFragment fragment = FrogmentFactory.getFragment(i);
            transaction.hide(fragment);

        }
        //深度解决fragment重影问题
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction beginTransaction = manager.beginTransaction();

        for (int i = 0; i < 4; i++) {
            Fragment one = manager.findFragmentByTag("one");
            if (one!=null) {
                beginTransaction.remove(one);
            }
        }
        beginTransaction.commit();


        //在点击的时候，先设置权不足为无按压状态
        noPressed();
        switch (view.getId()) {
            case R.id.first_home_home:
                BeasicFragment fragmenthome = FrogmentFactory.getFragment(0);
                if (!fragmenthome.isAdded()){
                    transaction.add(R.id.mian_mian_mian, fragmenthome, "one");
                }
                transaction.show(fragmenthome);
                firstHomeText.setTextColor(Color.parseColor("#000000"));
                firstHomeImage.setImageResource(R.mipmap.home_on);

                break;
            case R.id.second_shopping_shopping:
                BeasicFragment fragmentshopping = FrogmentFactory.getFragment(1);
                if (!fragmentshopping.isAdded()){
                    transaction.add(R.id.mian_mian_mian, fragmentshopping, "one");
                }
                transaction.show(fragmentshopping);
                secondShoppingText.setTextColor(Color.parseColor("#000000"));
                secondShoppingImage.setImageResource(R.mipmap.shopping_on);


                break;
            case R.id.tired_bag_bag:
                BeasicFragment fragmentbag = FrogmentFactory.getFragment(2);

                if (!fragmentbag.isAdded()){
                    transaction.add(R.id.mian_mian_mian, fragmentbag, "one");

                }
                transaction.show(fragmentbag);
                tiredBagText.setTextColor(Color.parseColor("#000000"));
                tiredBagImage.setImageResource(R.mipmap.shopping_bag_on);

                break;
            case R.id.four_me_me:
                BeasicFragment fragmentme = FrogmentFactory.getFragment(3);
                if (!fragmentme.isAdded()){
                    transaction.add(R.id.mian_mian_mian, fragmentme, "one");
                }
                transaction.show(fragmentme);
                fourMeText.setTextColor(Color.parseColor("#000000"));
                fourMeImage.setImageResource(R.mipmap.mine_on);

                break;

        }
        transaction.commit();
    }


    //判断按下的是否为返回键，并且是否按下

    /**
     * 这是退出工具
     *
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) &&
                (event.getAction() == KeyEvent.ACTION_DOWN)) {
            //如果两次按返回键时间间隔大于2000毫秒就吐司提示，否则finish（）当前Activity

            if ((System.currentTimeMillis() - tempTime) > 2000) {
                tempTime = System.currentTimeMillis();
                ToastMake.showToast("再按下就会退出.....");
            } else {
                finish();
                System.exit(0);//0表示正常退出，非0表示不正常
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取本地版本号，并进行更新
     */
    private void initData() {

        //不能再主线程中进行操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //1.进行网络请求获取json数据
                    Response response = HttpUtil.httpGet(URIpsot.apkDown);

                    String json = response.body().string();

                    //json解析
                    mInfoBeen = GsonUtil.parseJsonToBean(json, UpDataInfoBeen.class);
                    String version = mInfoBeen.getRemoteVersion();
                    int anInt = Integer.parseInt(version);

                    //2.进行版本号比对
                    int code = PackageUtil.getVersionCode(MainActivity.this, getPackageName());
                    if (anInt > code) {
                        //                    3.切换到主线程弹出提示框进行提示

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                //展示对话框
                                dailogShow();
                            }
                        });

                    } else {
                        //TODO:进入主界面

                    }

                } catch (Exception e) {
                    //TODO：返回到主界面
                    e.printStackTrace();
                    //                    Utils.runOnUIThread(new Runnable() {
                    //                        @Override
                    //                        public void run() {
                    //                            startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    //                        }
                    //                    });

                }
            }
        }).start();
    }

    //                    4.是否进行升级
    private void dailogShow() {
        MaterialDialog.Builder builder = new MaterialDialog.Builder(MainActivity.this);
        builder.title("更新提示");
        builder.content(mInfoBeen.getDesc());
        builder.negativeText("取消更新");
        builder.positiveText("确定更新");
        builder.onNegative(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                dialog.dismiss();
                //取消更新
                //TODO:进入主界面

            }
        });
        builder.onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                //开始更新
                dialog.dismiss();
                //  5.下载apk
                //弄个进度框，显示下载速度
                mProgressDialog = new ProgressDialog(MainActivity.this);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.show();
                //先判断sd卡是否存在
                mEquals = Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        downLadeApk();
                    }
                }).start();


            }
        });

        builder.show();
    }

    //下载apk文件
    private void downLadeApk() {

        if (mEquals) {
            //如果内存卡存在就下载到内存卡
            try {
                Response apk = HttpUtil.getImage(mInfoBeen.getApkurl());
                if (apk != null) {

                    mInputStream = apk.body().byteStream();
                    long max = apk.body().contentLength();
                    //设置进度条的最大值
                    mProgressDialog.setMax(100);
                    mAPKfile = new File(Environment.getExternalStorageDirectory(), "apktext.apk");
                    mOutputStream = new FileOutputStream(mAPKfile);
                    byte[] buffer = new byte[1024];
                    int len = 1;
                    while ((len = mInputStream.read(buffer)) != -1) {
                        mOutputStream.write(buffer, 0, len);
                        greelong += len;

                        //                        mProgressDialog.setProgress((int) (greelong/max)*100);
                        float v = greelong * 1.0f / max * 100;
                        mProgressDialog.setProgress((int) v);
                    }

                    mOutputStream.flush();
                    //对话框消失
                    mProgressDialog.dismiss();
                    //  6.提示用户安装
                    inStallApk();

                    // 7.安装完成
                } else {
                    //                    ToastMake.showToast("网路异常，更新失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
                //                ToastMake.showToast("网路异常，更新失败");
                //TODO：进入主界面
            } finally {

                //关流
                closeIO(mInputStream, mOutputStream);

            }
        } else {

        }
    }

    private void inStallApk() {
        //隐式意图安装的固定套路
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");

        //apk的文件名称
        Uri data = Uri.fromFile(mAPKfile);
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        //		startActivity(intent);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //监听客户是否安装,并且需要复写些onActivityResult方法
        startActivityForResult(intent, REQUEST_INSTALL);
        Process.killProcess(Process.myPid());
        /*
        *
  如果没有android.os.Process.killProcess(android.os.Process.myPid());最后不会提示完成、打开。没有这一句的话，安装完成后打开的不是新版本的apk

如果没有i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这一步的话，最后安装好了，点打开，是不会打开新版本应用的。*/


    }

    //关流
    private void closeIO(Closeable... io) {

        if (io != null) {
            for (int i = 0; i < io.length; i++) {

                if (io[i] != null) {
                    try {
                        io[i].close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        //TODO:进入主界面
                    }
                }
            }
        }
    }

    /**
     * 点击安装时是点击取消还是点击安装
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_INSTALL) {
            switch (resultCode) {
                //同意安装apk
                case Activity.RESULT_OK:

                    break;
                //取消安装apk
                case Activity.RESULT_CANCELED:

                    break;
            }
        }
    }
    /**
     * 1,先检查权限
     * 2，如果用户已经授权了，则可以直接登录
     * 3，如果用户没有，则申请，并自动跳转到相关界面
     */
    public void getUserPermission() {
        //读取手机设备信息权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            //没被授权,申请权限
            /**
             * 系统会弹出一个对话框，当用户回调或者拒绝时，会回调当前的一个方法
             */
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_PHONE_STATE},1);


        }
        //获取内存卡读取权限
        if (ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){

            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},2);

        }


    }

    /**
     * 获取权限返回请求结果
     * @param requestCode 对应上面的请求参数
     * @param permissions  所申请的权限组
     * @param grantResults  对应的结果组
     */

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

       //获得请求返回
        if (requestCode==1){


        }

        switch (requestCode){
            case 1:
                if (permissions[0]==Manifest.permission.READ_PHONE_STATE){

                    ToastMake.showToast("被授权了");

                    //TODO:获取手机设备型号ID进行验证见面的跳转
                    TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
                    String DEVICE_ID = tm.getDeviceId();
                    System.out.println(DEVICE_ID);


                }else {
                    ToastMake.showToast("被拒绝了");
                }
                break;
            case 2:
                if (permissions[0]==Manifest.permission.WRITE_EXTERNAL_STORAGE){

                    ToastMake.showToast("被授权了");

                    //TODO:获取手机内存卡读取权限


                }else {
                    ToastMake.showToast("被拒绝了");
                }
        }
    }
}
